package com.example.serializer;

import com.example.enums.ValueEnum;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;

import java.io.IOException;
import java.util.Objects;

/**
 * 自定义枚举序列化器，用于在序列化时添加文本字段
 * @JsonSerialize(using = AddFieldJsonSerializer.class, nullsUsing = AddFieldJsonSerializer.class)
 */
public class AddFieldJsonSerializer extends JsonSerializer<ValueEnum> {
    @Override
    public void serialize(ValueEnum valueEnum, JsonGenerator gen, SerializerProvider serializerProvider) throws IOException {
        // 获取当前字段名称
        String fieldName = gen.getOutputContext().getCurrentName();

        if (Objects.nonNull(valueEnum)) {
            // 写入原始字段的值
            gen.writeString(String.valueOf(valueEnum.getCode()));
        } else {
            gen.writeNull();
        }

        // 写入新增的文本字段
        gen.writeFieldName(fieldName.concat("Text"));
        if (Objects.nonNull(valueEnum)) {
            gen.writeString(valueEnum.getText());
        } else {
            gen.writeNull();
        }
    }
}